// $codepro.audit.disable logExceptions
/*
 * StoreFrameBackend.java
 * Team qq 2011
 */
package com.google.code.timetrail.presenter;

import java.awt.Color;

import com.google.code.timetrail.backend.Control;
import com.google.code.timetrail.backend.Inventory;
import com.google.code.timetrail.backend.Item;
import com.google.code.timetrail.backend.Store;

/**
 * @author MooglesRock@gmail.com
 * @version 1.0.0
 */
public class StoreFrameBackend {
	/**
	 * The color of the error in the store
	 */
	private static final Color ERROR_COLOR = Color.pink;

	/**
	 * THe color of when it is good in the store
	 */
	private static final Color GOOD_COLOR = Color.white;

	/**
	 * The location of the Bargaining skill within the skills array
	 */
	private static final int BARGAINING_SKILL_POSITION = 2;
	
	/**
	 * the maximum skill level
	 */
	private static final int MAX_SKILL_LEVEL = 100;
	
	/**
	 * The data for the game
	 */
	private final Control gameControl;

	/**
	 * The store
	 */
	private final Store store;

	/**
	 * The inventory for the player
	 */
	private final Inventory playerInv;

	/**
	 * The engine text field
	 */
	private String engineTextField;

	/**
	 * The FCapacitor text field
	 */
	private String fCapacitorTextField;

	/**
	 * The food text field
	 */
	private String foodTextField;

	/**
	 * The hull parts text field
	 */
	private String hullPartsTextField;

	/**
	 * The fuel cells text field
	 */
	private String fuelCellsTextField;

	/**
	 * THe clothing text field
	 */
	private String clothingTextField;

	/**
	 * The ammunition text field
	 */
	private String ammunitionTextField;

	/**
	 * The fuel cells amount
	 */
	private int fuelCellsAmount;

	/**
	 * The hull parts amount
	 */
	private int hullPartsAmount;

	/**
	 * The FCapacitor amount
	 */
	private int fCapacitorAmount;

	/**
	 * The ammunition amount
	 */
	private int ammunitionAmount;

	/**
	 * The clothing amount
	 */
	private int clothingAmount;

	/**
	 * The food amount
	 */
	private int foodAmount;

	/**
	 * The engine amount
	 */
	private int engineAmount;

	/**
	 * The validity of engine
	 */
	private boolean engineValid;

	/**
	 * The validity of FCapacitor
	 */
	private boolean fCapacitorValid;

	/**
	 * The validity of Fuel Cells
	 */
	private boolean fuelCellsValid;

	/**
	 * The validity of food
	 */
	private boolean foodValid;

	/**
	 * The validity of hull parts
	 */
	private boolean hullPartsValid;

	/**
	 * The validity of clothing
	 */
	private boolean clothingValid;

	/**
	 * The validity of ammunition
	 */
	private boolean ammunitionValid;

	/**
	 * Creates a new StoreFrameBackend
	 * 
	 * @param gameControl
	 *            the game data
	 */
	public StoreFrameBackend(Control gameControl) {
		this.store = new Store(gameControl);
		this.gameControl = gameControl;
		this.playerInv = this.gameControl.getInv();
		engineValid = true;
		fCapacitorValid = true;
		fuelCellsValid = true;
		foodValid = true;
		hullPartsValid = true;
		clothingValid = true;
		ammunitionValid = true;
		engineAmount = 0;
		fuelCellsAmount = 0;
		hullPartsAmount = 0;
		fCapacitorAmount = 0;
		ammunitionAmount = 0;
		clothingAmount = 0;
		foodAmount = 0;
		engineTextField = "0";
		fCapacitorTextField = "0";
		foodTextField = "0";
		hullPartsTextField = "0";
		fuelCellsTextField = "0";
		clothingTextField = "0";
		ammunitionTextField = "0";
	}

	/**
	 * Gets the Store label text
	 * 
	
	 * @return store label text */
	public String getStoreLabelText() {
		return "STORE";
	}

	/**
	 * Gets the Quantity label text
	 * 
	
	 * @return quantity label text */
	public String getQuantityLabelText() {
		return "Quantity";
	}

	/**
	 * Gets the Item name label text
	 * 
	
	 * @return item name label text */
	public String getItemNameLabelText() {
		return "Item";
	}

	/**
	 * Gets the price weight label text
	 * 
	
	 * @return price weight label text */
	public String getPriceWeightLabelText() {
		return "Price / Weight";
	}

	/**
	 * Gets the engine label text
	 * 
	
	 * @return engine label text */
	public String getEngineLabelText() {
		return playerInv.getEngines().toString();
	}

	/**
	 * Gets the food label text
	 * 
	
	 * @return food label text */
	public String getFoodLabelText() {
		return playerInv.getFood().toString();
	}

	/**
	 * Gets the clothing label text
	 * 
	
	 * @return clothing label text */
	public String getClothingLabelText() {
		return playerInv.getTimeSuits().toString();
	}

	/**
	 * Gets the ammunition label text
	 * 
	
	 * @return ammunition label text */
	public String getAmmunitionLabelText() {
		return playerInv.getTimeBulletBills().toString();
	}

	/**
	 * Gets the FCapacitor label text
	 * 
	
	 * @return FCapacitor label text */
	public String getFCapacitorLabelText() {
		return playerInv.getFCapacitors().toString();
	}

	/**
	 * Gets the Hull parts label text
	 * 
	
	 * @return hull parts label text */
	public String getHullPartsLabelText() {
		return playerInv.getHullParts().toString();
	}

	/**
	 * Gets the Fuel cells label text
	 * 
	
	 * @return fuel cells label text */
	public String getFuelCellsLabelText() {
		return playerInv.getFuelCells().toString();
	}

	/**
	 * Get the food price weight
	 * 
	
	 * @return food price weight */
	public String getFoodPriceWeight() {
	    final Item food = playerInv.getFood();
		return ("$" + (food.getValue() - 
		        ((food.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getFood().getWeight() + " lb.");
	}

	/**
	 * Get the engine price weight
	 * 
	
	 * @return engine price weight */
	public String getEnginePriceWeight() {
	    final Item engines = playerInv.getEngines();
		return ("$" + (engines.getValue() 
		        - ((engines.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + (" N/A");
	}

	/**
	 * Get the Clothing price weight
	 * 
	
	 * @return clothing price weight */
	public String getClothingPriceWeight() {
	    final Item timeSuits = playerInv.getTimeSuits();
		return ("$" + (timeSuits.getValue() 
		        - ((timeSuits.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getTimeSuits().getWeight() + " lb.");
	}

	/**
	 * Get the Ammunition price weight
	 * 
	
	 * @return ammunition price weight */
	public String getAmmunitionPriceWeight() {
	    final Item timeBulletBills = playerInv.getTimeBulletBills();
		return ("$" + (timeBulletBills.getValue() 
		        - ((timeBulletBills.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getTimeBulletBills().getWeight() + " lb.");
	}

	/**
	 * Get the FCapacitors price weight
	 * 
	
	 * @return fcapacitors price weight */
	public String getFCapacitorsPriceWeight() {
	    final Item fCapacitors = playerInv.getFCapacitors();
		return ("$" + (fCapacitors.getValue() 
		        - ((fCapacitors.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getFCapacitors().getWeight() + " lb.");
	}

	/**
	 * Get the Hull parts price weight
	 * 
	
	 * @return hull parts price weight */
	public String getHullPartsPriceWeight() {
	    final Item hullParts = playerInv.getHullParts();
		return ("$" + (hullParts.getValue() 
		        - ((hullParts.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getHullParts().getWeight() + " lb.");
	}

	/**
	 * Get the Fuel cells price weight
	 * 
	
	 * @return fuel cells price weight */
	public String getFuelCellsPriceWeight() {
	    final Item fuelCells = playerInv.getFuelCells();
		return ("$" + (fuelCells.getValue() 
		        - ((fuelCells.getValue() 
		                * gameControl.getPlayer().getSkills()
		                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL)) + " / "
				+ (playerInv.getFuelCells().getWeight() + " lb.");
	}

	/**
	 * Get the total weight label
	 * 
	
	 * @return total weight label */
	public String getTotalWeightLabel() {
		return "Total Weight: " + getWeightTotal();
	}

	/**
	 * Calculates the total weight
	 * 
	
	 * @return total weight */
	private int getWeightTotal() {
		final int engineWeight = engineAmount * playerInv.getEngines().getWeight();
		final int hullPartWeight = hullPartsAmount
				* playerInv.getHullParts().getWeight();
		final int timeSuitWeight = clothingAmount
				* playerInv.getTimeSuits().getWeight();
		final int timeBulletBillWeight = ammunitionAmount
				* playerInv.getTimeBulletBills().getWeight();
		final int fuelCellWeight = fuelCellsAmount
				* playerInv.getFuelCells().getWeight();
		final int fCapacitorWeight = fCapacitorAmount
				* playerInv.getFCapacitors().getWeight();
		final int foodWeight = foodAmount * playerInv.getFood().getWeight();
		return engineWeight + hullPartWeight + timeSuitWeight
				+ timeBulletBillWeight + fuelCellWeight + fCapacitorWeight
				+ foodWeight;
	}

	/**
	 * Get the Total cost label
	 * 
	
	 * @return total cost label */
	public String getTotalCostLabel() {
		return "Total Cost: " + getCostTotal();
	}

	/**
	 * Calculates the total cost
	 * 
	
	 * @return total cost */
	private int getCostTotal() {
	    final Item engines = playerInv.getEngines();
	    final Item hullParts = playerInv.getHullParts();
	    final Item timeSuits = playerInv.getTimeSuits();
	    final Item timeBulletBills = playerInv.getTimeBulletBills();
	    final Item fuelCells = playerInv.getFuelCells();
	    final Item fCapacitors = playerInv.getFCapacitors();
	    final Item food = playerInv.getFood();
		final int engineCost = engineAmount 
		        * (engines.getValue() 
		                - ((engines.getValue() 
		                        * gameControl.getPlayer().getSkills()
		                        [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int hullPartCost = hullPartsAmount
				* (hullParts.getValue() 
				        - ((hullParts.getValue() 
				                * gameControl.getPlayer().getSkills()
				                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int timeSuitCost = clothingAmount 
		        * (timeSuits.getValue() 
		                - ((timeSuits.getValue() 
		                        * gameControl.getPlayer().getSkills()
		                        [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int timeBulletBillCost = ammunitionAmount
				* (timeBulletBills.getValue() 
				        - ((timeBulletBills.getValue() 
				                * gameControl.getPlayer().getSkills()
				                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int fuelCellCost = fuelCellsAmount
				* (fuelCells.getValue() 
				        - ((fuelCells.getValue() 
				                * gameControl.getPlayer().getSkills()
				                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int fCapacitorCost = fCapacitorAmount
				* (fCapacitors.getValue() 
				        - ((fCapacitors.getValue() 
				                * gameControl.getPlayer().getSkills()
				                [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		final int foodCost = foodAmount 
		        * (food.getValue() 
		                - ((food.getValue() 
		                        * gameControl.getPlayer().getSkills()
		                        [BARGAINING_SKILL_POSITION ])) / MAX_SKILL_LEVEL);
		return engineCost + hullPartCost + timeSuitCost + timeBulletBillCost
				+ fuelCellCost + fCapacitorCost + foodCost;
	}

	/**
	 * Gets the money label
	 * 
	
	 * @return money label */
	public String getMoneyLabel() {
		return "Money:" + playerInv.getMoney().getCurrentAmount();
	}

	/**
	 * Gets the next button text
	 * 
	
	 * @return next button text */
	public String getNextButtonText() {
		return "Next >>";
	}

	/**
	 * Actions for the pressing the next button
	
	 * @throws NumberFormatException */
	public void pressNextButton() throws NumberFormatException{
	    try{
		store.setTempEngines(Integer.parseInt(engineTextField));
		store.setTempFCapacitors(Integer.parseInt(fCapacitorTextField));
		store.setTempFood(Integer.parseInt(foodTextField));
		store.setTempHullParts(Integer.parseInt(hullPartsTextField));
		store.setTempFuelCells(Integer.parseInt(fuelCellsTextField));
		store.setTempTimeSuits(Integer.parseInt(clothingTextField));
		store.setTempTimeBulletBills(Integer.parseInt(ammunitionTextField));
	    } catch (NumberFormatException e){
	        System.err.println(e);
	    }
		if (store.canBuyItem(Integer.parseInt(fuelCellsTextField), gameControl
				.getInv().getFuelCells())) {
			store.buyItem(Integer.parseInt(fuelCellsTextField), gameControl
					.getInv().getFuelCells());
		}

		if (store.canBuyItem(Integer.parseInt(hullPartsTextField), gameControl
				.getInv().getHullParts())) {
			store.buyItem(Integer.parseInt(hullPartsTextField), gameControl
					.getInv().getHullParts());
		}

		if (store.canBuyItem(Integer.parseInt(foodTextField), gameControl
				.getInv().getFood())) {
			store.buyItem(Integer.parseInt(foodTextField), gameControl.getInv()
					.getFood());
		}

		if (store.canBuyItem(Integer.parseInt(engineTextField), gameControl
				.getInv().getEngines())) {
			store.buyItem(Integer.parseInt(engineTextField), gameControl
					.getInv().getEngines());
		}

		if (store.canBuyItem(Integer.parseInt(fCapacitorTextField), gameControl
				.getInv().getFCapacitors())) {
			store.buyItem(Integer.parseInt(fCapacitorTextField), gameControl
					.getInv().getFCapacitors());
		}

		if (store.canBuyItem(Integer.parseInt(clothingTextField), gameControl
				.getInv().getTimeSuits())) {
			store.buyItem(Integer.parseInt(clothingTextField), gameControl
					.getInv().getTimeSuits());
		}

		if (store.canBuyItem(Integer.parseInt(ammunitionTextField), gameControl
				.getInv().getTimeBulletBills())) {
			store.buyItem(Integer.parseInt(ammunitionTextField), gameControl
					.getInv().getTimeBulletBills());
		}
		if(gameControl.getInv().canRemoveItem(getCostTotal(), 
		        gameControl.getInv().getMoney())){
		gameControl.getInv().removeItem(getCostTotal(), gameControl.getInv().getMoney());
		}
		// TODO Set up moving to the next card
	}

	/**
	 * Gets the back button text
	 * 
	
	 * @return back button text */
	public String getBackButtonText() {
		return "Back <<";
	}

	/**
	 * Actions for the pressing the back button
	 */
	public void pressBackButton() { // This is a temporary method filler and
									// needs to be properly done
		// TODO set up moving to the previous card
		for (int i = 0; i < 1; i++) {
			i++;
		}
	}

	/**
	 * Checks if it can enable next button
	 * 
	
	 * @return true if next button can be enabled or not */
	public boolean canEnableNextButton() {
		return engineValid && fCapacitorValid && fuelCellsValid && foodValid
				&& hullPartsValid && clothingValid && ammunitionValid;
	}

	/**
	 * Sets the text for the engine field
	 * 
	 * @param text
	 *            for the engine text field
	 */
	public void setEngineTextField(String text) {
		this.engineTextField = text;
	}

	/**
	 * Figures out the color for the engine text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getEngineTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(engineTextField)) {
			engineValid = false;
			return ERROR_COLOR;
		}
		engineAmount = Integer.parseInt(engineTextField);
		if (engineAmount > playerInv.getEngines().getMaxAmount()) {
			engineValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			engineValid = true;
			return GOOD_COLOR;
		} else {
			if (engineAmount != 0) {
				engineValid = false;
				return ERROR_COLOR;
			}
			engineValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the food field
	 * 
	 * @param text
	 *            for the food text field
	 */
	public void setfoodTextField(String text) {
		this.foodTextField = text;
	}

	/**
	 * Figures out the color for the food text field
	 * 

	 * @return the appropriate color for the field 
	 * @throws NumberFormatException
	 */
	public Color getFoodTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(foodTextField)) {
			foodValid = false;
			return ERROR_COLOR;
		}
		foodAmount = Integer.parseInt(foodTextField);
		if (foodAmount > playerInv.getFood().getMaxAmount()) {
			foodValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			foodValid = true;
			return GOOD_COLOR;
		} else {
			if (foodAmount != 0) {
				foodValid = false;
				return ERROR_COLOR;
			}
			foodValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the clothing field
	 * 
	 * @param text
	 *            for the clothing text field
	 */
	public void setClothingTextField(String text) {
		this.clothingTextField = text;
	}

	/**
	 * Figures out the color for the clothing text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getClothingTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(clothingTextField)) {
			clothingValid = false;
			return ERROR_COLOR;
		}
		clothingAmount = Integer.parseInt(clothingTextField);
		if (clothingAmount > playerInv.getTimeSuits().getMaxAmount()) {
			clothingValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			clothingValid = true;
			return GOOD_COLOR;
		} else {
			if (clothingAmount != 0) {
				clothingValid = false;
				return ERROR_COLOR;
			}
			clothingValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the ammunition field
	 * 
	 * @param text
	 *            for the ammunition text field
	 */
	public void setAmmunitionTextField(String text) {
		this.ammunitionTextField = text;
	}

	/**
	 * Figures out the color for the ammunition text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getAmmunitionTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(ammunitionTextField)) {
			ammunitionValid = false;
			return ERROR_COLOR;
		}
		ammunitionAmount = Integer.parseInt(ammunitionTextField);
		if (ammunitionAmount > playerInv.getTimeBulletBills().getMaxAmount()) {
			ammunitionValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			ammunitionValid = true;
			return GOOD_COLOR;
		} else {
			if (ammunitionAmount != 0) {
				ammunitionValid = false;
				return ERROR_COLOR;
			}
			ammunitionValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the fcapacitor field
	 * 
	 * @param text
	 *            for the fcapacitor text field
	 */
	public void setFCapacitorTextField(String text) {
		this.fCapacitorTextField = text;
	}

	/**
	 * Figures out the color for the fcapacitor text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getFCapacitorTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(fCapacitorTextField)) {
			fCapacitorValid = false;
			return ERROR_COLOR;
		}
		fCapacitorAmount = Integer.parseInt(fCapacitorTextField);
		if (fCapacitorAmount > playerInv.getFCapacitors().getMaxAmount()) {
			fCapacitorValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			fCapacitorValid = true;
			return GOOD_COLOR;
		} else {
			if (fCapacitorAmount != 0) {
				fCapacitorValid = false;
				return ERROR_COLOR;
			}
			fCapacitorValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the hull parts field
	 * 
	 * @param text
	 *            for the hull parts text field
	 */
	public void setHullPartsTextField(String text) {
		this.hullPartsTextField = text;
	}

	/**
	 * Figures out the color for the hull parts text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getHullPartsTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(hullPartsTextField)) {
			hullPartsValid = false;
			return ERROR_COLOR;
		}
		try{
		    hullPartsAmount = Integer.parseInt(hullPartsTextField);
		} catch (NumberFormatException e){
            System.err.println(e);
        }
		if (hullPartsAmount > playerInv.getHullParts().getMaxAmount()) {
			hullPartsValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			hullPartsValid = true;
			return GOOD_COLOR;
		} else {
			if (hullPartsAmount != 0) {
				hullPartsValid = false;
				return ERROR_COLOR;
			}
			hullPartsValid = true;
			return GOOD_COLOR;
		}
	}

	/**
	 * Sets the text for the fuel cells field
	 * 
	 * @param text
	 *            for the fuel cells text field
	 */
	public void setFuelCellsTextField(String text) {
		this.fuelCellsTextField = text;
	}

	/**
	 * Figures out the color for the fuel cells text field
	 * 

	 * @return the appropriate color for the field
	 * @throws NumberFormatException
	 */
	public Color getFuelCellsTextFieldColor() throws NumberFormatException{
		if (!isValidEntry(fuelCellsTextField)) {
			fuelCellsValid = false;
			return ERROR_COLOR;
		}
		try{
		fuelCellsAmount = Integer.parseInt(fuelCellsTextField);
		} catch (NumberFormatException e){
		    System.err.println(e);
		}
		if (fuelCellsAmount > playerInv.getFuelCells().getMaxAmount()) {
			fuelCellsValid = false;
			return ERROR_COLOR;
		}
		if (canBuyFromStore()) {
			fuelCellsValid = true;
			return GOOD_COLOR;
		} else {
			if (fuelCellsAmount != 0) {
				fuelCellsValid = false;
				return ERROR_COLOR;
			}
			fuelCellsValid = true;
			return GOOD_COLOR;
		}

	}

	/**
	 * Checks if you can buy from the store or not
	
	 * @return true if you can buy from the store and vice versa */
	private boolean canBuyFromStore() {
		final int weightRemaining = playerInv.getCapacity()
				- playerInv.getInvWeight();
		final int playerMoney = playerInv.getMoney().getCurrentAmount();
		return (playerMoney >= getCostTotal() && weightRemaining >= getWeightTotal());
	}

	/**
	 * Checks if it is a valid entry or not
	 * @param entry The entry that needs to validated
	
	 * @return true if the entry is valid */
	public boolean isValidEntry(String entry) {
		try {
			final int val = Integer.parseInt(entry);
			return val >= 0;
		} catch (NumberFormatException e) {
			//System.err.println("entry is not valid");
			return false;
		}
	}

	/**
	 * Returns the name of the class
	
	 * @return name of the class */
	@Override
	public String toString() {
		return "StoreFrameBackend";
	}
}
